package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.DeleteFlag;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.MerchantReach20StatusEnum;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.core.exception.BizRuntimeException;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.MerchantReach20;
import com.yourenbang.lingyun.domain.MerchantReach20Example;
import com.yourenbang.lingyun.mapper.MerchantReach20Mapper;
import com.yourenbang.lingyun.mapper.UserBaseExtMapper;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.MigrateDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.klks.UserReach;
import com.yourenbang.lingyun.transaction.web.service.migrate.MerchantReachMigrateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service("merchantReachMigrateService")
public class MerchantReachMigrateServiceImpl extends AbstractMigrateService implements MerchantReachMigrateService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private UserBaseExtMapper userBaseExtMapper;
    @Autowired
    private MerchantReach20Mapper merchantReach20Mapper;

    /**
     * 阶段达标
     */
    @Override
    public void userReach(MigrateDTO dto) {
        if(StringUtils.equals(dto.getOpt(), MigrateDTO.OPT_INSERT)){
            merchantReachInsert(dto);
        }else if(StringUtils.equals(dto.getOpt(), MigrateDTO.OPT_UPDATE)){
            merchantReachUpdate(dto);
        }else if(StringUtils.equals(dto.getOpt(), MigrateDTO.OPT_DELETE)){
            merchantReachDelete(dto);
        }else {
            KLog.error("[MQ-商户-考拉快收-数据同步]阶段达标,不支持的数据操作入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的数据操作");
        }
    }

    /**
     * 阶段达标插入
     * 必须参数：ProductType，User_id, stage
     */
    private void merchantReachInsert(MigrateDTO dto){
        UserReach userReach = JSONObject.parseObject(dto.getData(), UserReach.class);
        if(userReach==null){
            KLog.error("[商户-考拉快收-数据同步]阶段达标插入,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if(StringUtils.isAnyBlank(userReach.getUserId(), userReach.getProductType(), userReach.getStage()+"")){
            KLog.error("[商户-考拉快收-数据同步]阶段达标插入,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, userReach.getUserId(), redis);
        if(StringUtils.isBlank(userBaseId)){
            KLog.error("[商户-考拉快收-数据同步]阶段达标插入,未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        MerchantReach20Example reach20Example = new MerchantReach20Example();
        reach20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andStageEqualTo(userReach.getStage())
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(userReach.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode())
                .andIsDelNotEqualTo(DeleteFlag.TRUE);
        List<MerchantReach20> oldMerchantReachList = merchantReach20Mapper.selectByExample(reach20Example);
        if(!CollectionUtils.isEmpty(oldMerchantReachList)){
            KLog.warn("[商户-考拉快收-数据同步]阶段达标插入,已存在该数据数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "已存在该数据");
        }

        MerchantReach20 merchantReach = fmtMerchantReach20Data(userReach, userBaseId);
        int inCount = merchantReach20Mapper.insertSelective(merchantReach);
        BizAssertUtils.assertOne(inCount, "添加达标数据失败");
    }

    /**
     * 阶段达标更新
     * 必须参数：ProductType，User_id, stage
     */
    private void merchantReachUpdate(MigrateDTO dto){
        UserReach userReach = JSONObject.parseObject(dto.getData(), UserReach.class);
        if(userReach==null){
            KLog.error("[商户-考拉快收-数据同步]阶段达标更新,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if(StringUtils.isAnyBlank(userReach.getUserId(), userReach.getProductType(), userReach.getStage()+"")){
            KLog.error("[商户-考拉快收-数据同步]阶段达标更新,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, userReach.getUserId(), redis);
        if(StringUtils.isBlank(userBaseId)){
            KLog.error("[商户-考拉快收-数据同步]阶段达标更新,未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        MerchantReach20Example reach20Example = new MerchantReach20Example();
        reach20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andStageEqualTo(userReach.getStage())
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(userReach.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode())
                .andIsDelNotEqualTo(DeleteFlag.TRUE);
        List<MerchantReach20> oldMerchantReachList = merchantReach20Mapper.selectByExample(reach20Example);

        if (CollectionUtils.isEmpty(oldMerchantReachList)) {
            if (StringUtils.equalsAny(userReach.getProductType(), "05", "08")) {
                MerchantReach20Example epoareach20Example = new MerchantReach20Example();
                if (StringUtils.equals(userReach.getProductType(), "05")) {
                    epoareach20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andStageEqualTo(userReach.getStage())
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("08").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }else if (StringUtils.equals(userReach.getProductType(), "08")) {
                    epoareach20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andStageEqualTo(userReach.getStage())
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("05").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }
                oldMerchantReachList = merchantReach20Mapper.selectByExample(epoareach20Example);
            }
        }

        if(CollectionUtils.isEmpty(oldMerchantReachList)){
            KLog.error("[商户-考拉快收-数据同步]阶段达标更新,未找到原阶段达标数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未找到原阶段达标数据");
        }
        MerchantReach20 oldMerchantReach = oldMerchantReachList.get(0);
        MerchantReach20 upReach = fmtMerchantReach20Data(userReach, userBaseId);
        upReach.setMerchantReachId(oldMerchantReach.getMerchantReachId());
        int upCount = merchantReach20Mapper.updateByPrimaryKeySelective(upReach);
        BizAssertUtils.assertOne(upCount, "更新阶段达标失败");
    }

    /**
     * 阶段达标删除
     * 必须参数：ProductType，User_id, stage
     */
    private void merchantReachDelete(MigrateDTO dto){
        KLog.error("[商户-考拉快收-数据同步]阶段达标删除,不支持的数据操作,入参:{}", dto.toJSON());
        UserReach userReach = JSONObject.parseObject(dto.getData(), UserReach.class);
        if(userReach==null){
            KLog.error("[商户-考拉快收-数据同步]阶段达标删除,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if(StringUtils.isAnyBlank(userReach.getUserId(), userReach.getProductType(), userReach.getStage()+"")){
            KLog.error("[商户-考拉快收-数据同步]阶段达标删除,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, userReach.getUserId(), redis);
        if(StringUtils.isBlank(userBaseId)){
            KLog.error("[商户-考拉快收-数据同步]阶段达标删除,未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        MerchantReach20Example reach20Example = new MerchantReach20Example();
        reach20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andStageEqualTo(userReach.getStage())
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(userReach.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode())
                .andIsDelNotEqualTo(DeleteFlag.TRUE);
        int deCount = merchantReach20Mapper.deleteByExample(reach20Example);
        BizAssertUtils.assertOne(deCount, "删除阶段达标失败");
    }

    /**
     * 格式化阶段达标数据
     */
    @Override
    public MerchantReach20 fmtMerchantReach20Data(UserReach userReach, String userBaseId){
        MerchantReach20 merchantReach = new MerchantReach20();
        merchantReach.setUserBaseId(userBaseId);
        merchantReach.setMerchantNo(userReach.getMerNo());
        merchantReach.setPhone(userReach.getPhone());
        merchantReach.setName(userReach.getName());
        merchantReach.setActiveTime(userReach.getActiveTime());
        merchantReach.setAssessBeginTime(userReach.getAssessBeginTime());
        merchantReach.setStage(userReach.getStage());
        merchantReach.setTargetAmount(userReach.getTargetAmount());
        merchantReach.setBeginTime(userReach.getBeginTime());
        merchantReach.setEndTime(userReach.getEndTime());
        merchantReach.setStatus(fmtMerchantReachStatus(userReach.getStatus()));
        merchantReach.setReachAmount(userReach.getReachAmt());
        merchantReach.setReachTime(userReach.getReachTime());
        merchantReach.setMerchantReachPolicyId(0);
        merchantReach.setChannelId(ChannelIdEnums.convertKuaiShouProductType(userReach.getProductType()).getCode());
        merchantReach.setIsDel(Constant.NORMAL);
        merchantReach.setPlatNo(PlatNoEnums.KLKS.getCode());
        merchantReach.setCreateTime(userReach.getCreateTime());
        merchantReach.setUpdateTime(userReach.getUpdateTime() == null ?
                LocalDateTime.now() : userReach.getUpdateTime());
        return merchantReach;
    }

    /**
     * 格式化阶段达标状态
     */
    private Short fmtMerchantReachStatus(String klksStatus){
        if(StringUtils.isBlank(klksStatus)){
            return null;
        }
        if(StringUtils.equals(klksStatus, UserReach.STATUS_0)){
            return MerchantReach20StatusEnum.STATUS_0.getCode();
        }else if(StringUtils.equals(klksStatus, UserReach.STATUS_1)){
            return MerchantReach20StatusEnum.STATUS_10.getCode();
        }else if(StringUtils.equals(klksStatus, UserReach.STATUS_2)){
            return MerchantReach20StatusEnum.STATUS_20.getCode();
        }else {
            KLog.error("[商户-考拉快收-数据同步]格式化阶段达标状态,不支持的阶段达标状态,入参:{}", klksStatus);
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的阶段达标状态");
        }
    }

}
